<template>
  <div ref="wrapRef" :class="getWrapperClass">
    <div class="co_table__header" v-if='useSearchForm'>
      <!-- 搜索 -->
      <co-basic-form class='co_table_searchform' ref='basicFormRef' v-bind='searchForm' @searchForm='search' @resetForm='resetForm' @exportFile='exportFile' :initFormData='initFormData'></co-basic-form>
    </div>

    <content class="c-content clearfix">
      <div class='co_table__toolbar'>
        <slot name="toolbar"></slot>
      </div>
      <!-- 表格 -->
      <el-table ref="tableElRef" :data="listData" v-bind="tableAttr" v-on="$listeners" class='co_basic_table'>

        <el-table-column label="序号" type="index" width="50">
        </el-table-column>

        <el-table-column v-if='showSelection' type="selection" width="55">
        </el-table-column>

        <!-- <template v-if='model'></template> -->
        <template v-for="column in columns">
          <template v-if='!column.isHide || !column.isHide()'>
            <el-table-column v-if='!column.customRender' :key="column.dataIndex" v-bind='column'></el-table-column>
            <el-table-column v-else :key="column.dataIndex" v-bind='column'>
              <template slot-scope="scope">
                <co-table-col :column='column' :scope='scope'></co-table-col>
              </template>
            </el-table-column>
          </template>
        </template>

        <template v-for="item in Object.keys($slots)">
          <slot :name="item"></slot>
        </template>
      </el-table>
      <!-- 分页 -->
      <div class="block" v-if='usePagination'>
        <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="queryCondition.pageRequest.pageIndex" :page-sizes="pageSizes" :page-size="queryCondition.pageRequest.limit" layout="total, sizes, prev, pager, next, jumper" :total="queryCondition.pageRequest.results">
        </el-pagination>
      </div>
    </content>

  </div>
</template>

<script>
import api from '../../../api/api'
import CoBasicForm from '../co-form/co-basic-form'
import CoTableCol from './co-table-col'
import util from '@/assets/js/co-util.js'
export default {
  name: 'co-table',
  props: {
    dataSource: {
      type: Array,
      default: () => []
    },
    // 搜索表单的默认值
    initFormData: {
      type: Object,
      default: () => { }
    },
    columns: {
      type: Array,
      default: () => []
    },
    searchForm: {
      type: Object,
      default: () => { }
    },
    // 接口地址服务名+方法名
    apiName: {
      type: String
    },
    // 请求结果返回的列表字段名
    listResultName: {
      type: String,
      default: 'data'
    },
    usePagination: {
      type: Boolean,
      default: true
    },
    useSearchForm: {
      type: Boolean,
      default: true
    },
    pageSizes: {
      type: Array,
      default: () => [10, 20, 30, 40]
    },
    tableAttr: {
      type: Object
    },
    // 请求之前处理参数
    beforeFetch: Function,
    // 自定义处理接口返回参数
    afterFetch: Function,
    showSelection: {
      type: Boolean,
      default: false
    },
    // 是否展示序号
    showIndex: {
      type: Boolean,
      default: false
    },
    // 是否立即查询
    immediate: {
      type: Boolean,
      default: true
    }
  },
  components: { CoBasicForm, CoTableCol },
  data () {
    return {
      // 页面查询条件
      queryCondition: {
        pageRequest: api.crud.getQueryCondition()
      },
      listData: [],
      defaultVals: {}
    }
  },
  computed: {
    getWrapperClass () {
      return [
        'co_table_page',
        this.$attrs.class
      ]
    }
  },
  watch: {
    dataSource (newVal) {
      console.log('-newVal--', newVal)
      this.listData = newVal
    }
  },
  created () {

  },
  mounted () {
    // 设置搜索表单的默认值
    let jsonStr = JSON.stringify(this.initFormData)
    if (jsonStr && jsonStr !== '{}') {
      this.setDefaultValue(this.initFormData)
    }

    if (this.dataSource && this.dataSource.length > 0) {
      this.listData = this.dataSource
    } else if (this.apiName && this.immediate) {
      this.$nextTick(() => {
        this.getListData()
      })
    }
  },
  methods: {
    handleSizeChange (limit) {
      this.queryCondition.pageRequest.limit = limit
      this.queryCondition.pageRequest = api.crud.getQueryCondition(this.queryCondition.pageRequest)
      this.getListData()
    },
    handleCurrentChange (pageIndex) {
      this.queryCondition.pageRequest.pageIndex = pageIndex
      this.queryCondition.pageRequest = api.crud.getQueryCondition(this.queryCondition.pageRequest)
      this.getListData()
    },
    setDataSource (arr) {
      this.listData = arr
    },
    getDataSource () {
      return this.listData
    },
    resetForm () {
      this.$refs.basicFormRef.resetFields()
      let jsonStr = JSON.stringify(this.defaultVals)
      if (jsonStr && jsonStr !== '{}') {
        this.$refs.basicFormRef.setFieldsValue(JSON.parse(jsonStr))
      }
      if (this.queryCondition.pageRequest) this.queryCondition.pageRequest = api.crud.getQueryCondition()
      this.getListData()
    },
    search () {
      this.getListData()
    },
    setDefaultValue (model) {
      this.defaultVals = model
      this.$refs.basicFormRef.setFieldsValue(JSON.parse(JSON.stringify(model)))
    },
    getSearchParam () {
      let param = {}
      if (this.usePagination) {
        param = Object.assign({}, this.queryCondition)
      }
      if (this.useSearchForm) {
        param = Object.assign({}, param, this.$refs.basicFormRef.getFormData())
      }
      if (this.beforeFetch) {
        param = this.beforeFetch(param)
      }
      util.dealEmptyQueryCondition(param)
      return param
    },
    exportFile () {
      let param = this.getSearchParam()
      this.$emit('exportFile', param)
      // api.crud.post({
      //   type: 'get',
      //   data: param,
      //   url: '/api/admin/store/exportStoreMonitorDailySaleTargetInfo.html',
      //   contentType: 'application/x-www-form-urlencoded',
      //   responseType: 'blob'
      // }).then(res => {
      //   const date = util.getSpecDate()
      //   const fileName = `${date}_门店经营目标表.xlsx`
      //   const url = URL.createObjectURL(res)
      //   util.downloadFile(url, fileName)
      // })
    },
    getListData () {
      let param = this.getSearchParam()
      let fun = api
      let arr = this.apiName.split('.')
      arr.forEach(it => {
        fun = fun[it]
      })
      if (!fun || typeof fun !== 'function') {
        throw new Error('方法不存在,请检查配置')
      }
      fun({
        data: {
          request: param
        }
      }).then(response => {
        let success = response.success
        let data = success[this.listResultName]
        if (this.afterFetch) {
          data = this.afterFetch(data) || data
        }
        this.listData = data
        this.queryCondition.pageRequest = api.crud.getCurrentPage(success.pageResponse)
      })
    }
  }
}
</script>

<style lang="scss">
.co_table_page {
  .co_table__header {
    padding: 15px 15px 0;
    background: white;
    width: 100%; // margin: 30px0;
    border-radius: 0 0 8px 8px;
    box-shadow: 0px 1px 2px 0px #c4ccd6; // 展开搜索显示
    .el-collapse-item__header {
      border-bottom: 0;
      color: #19bf4f;
      font-weight: 700;
      font-family: "冬青黑体简体中文W6";
      font-size: 14px;
      height: 30px;
      line-height: 30px;
      .el-collapse-item__arrow {
        line-height: 30px;
      }
    }
    .el-collapse {
      border-bottom: 0;
      border-top: 0;
    }
    .el-collapse-item__wrap {
      border-bottom: 0;
    } // 表单
  }

  .co_table_searchform {
    .el-col {
      margin-bottom: 10px;

      .el-form-item {
        .el-form-item__label {
          min-width: 88px;
        }
        .el-form-item__content {
          margin-left: 88px;
          line-height: 38px;
        }
      }
    }
  }
}
</style>
